<?php
// +----------------------------------------------------------------------
// | B5Yii2CMF V3.0 [快捷通用基础管理开发平台]
// +----------------------------------------------------------------------
// | Author=>冰舞 <357145480@qq.com>
// +----------------------------------------------------------------------
declare (strict_types=1);

namespace api\modules\admin\controllers\system;

use api\modules\admin\AuthController;
use api\utils\libs\CommonAction;
use common\models\system\Admin;
use common\services\PermissionService;
use common\services\system\AdminService;
use common\services\system\DeptService;
use Yii;
use yii\db\ActiveQuery;
use yii\db\Expression;

class AdminController extends AuthController
{
    use CommonAction;

    protected string $model = Admin::class;
    protected bool $validate = true;

    protected function listBefore(array $params): array
    {
        $params['alias'] = 'u';
        $params['debug'] = 1;
        $params['isActive'] = 1;
        return $params;
    }

    protected function listQuery(ActiveQuery $query): ActiveQuery
    {

        $deptId = $this->request->post('deptId', '');
        $contain = intval($this->request->post('contain', 0));
        $rootDeptId = Yii::$app->params['root_dept_id'];
        $deptWhere = [];

        // 当不是超级管理员时，指定权限内的部门
        if (!PermissionService::isAdmin($this->user_id)) {
            $userDeptList = DeptService::selectDeptByUserId($this->user_id);
            if (!$userDeptList) return $query->andWhere(['u.id'=>0]);
            $isRoot = false;
            $userValidDeptId = [];
            foreach ($userDeptList as $dept) {
                if ($dept['id'] == $rootDeptId) {
                    $isRoot = true;
                    break;
                }
                $userValidDeptId[] = $dept['id'];
            }
            if (!$isRoot) {
                if (!$userValidDeptId) return $query->andWhere(['u.id'=>0]);
                $where = ['or'];
                foreach ($userValidDeptId as $userDeptId) {
                    $where[] = ['s.id' => $userDeptId];
                    $where[] = new Expression('FIND_IN_SET("' . $userDeptId . '", s.levels)');
                }
                $deptWhere[] = $where;
            }
        }

        if ($deptId) {
            if (!$contain) {
                $deptWhere[] = ['s.id' => $deptId];
            } elseif ($deptId != $rootDeptId) {
                $deptWhere[] = ['or', ['s.id' => $deptId], new Expression('FIND_IN_SET("' . $deptId . '", s.levels)')];
            }
        }

        if ($deptWhere) {
            $query = $query->joinWith([
                'deptList s' => function ($q) use ($deptWhere) {
                    foreach ($deptWhere as $value) {
                        $q->andWhere($value);
                    }
                }
            ]);
        }
        return $query->distinct();
    }

    /**
     * @param Admin[] $list
     * @return array
     */
    protected function listAfter(array $list): array
    {
        foreach ($list as $key => $value) {
            $arr = $value->toArray();
            $arr['deptName'] = $value->deptList ? array_column($value->deptList, 'name') : [];
            $arr['roleName'] = $value->roleList ? array_column($value->roleList, 'name') : [];
            $list[$key] = $arr;
        }
        return $list;
    }

    protected function infoAfter(Admin $model): array
    {
        $info = $model->toArray();
        $info['roleIds'] = $model->roleLink ? array_column($model->roleLink, 'role_id') : [];
        $info['postIds'] = $model->posLink ? array_column($model->posLink, 'pos_id') : [];
        $info['dept'] = $model->deptOne ?: [];
        $info['deptId'] = $model->deptLink ? $model->deptOne->id : '';
        return $this->success('', ['info' => $info]);
    }

    protected function validateBefore(Admin $model, string $type): string
    {
        if ($type == 'edit') $model->scenario = 'edit';
        return '';
    }

    
    protected function loadBefore(array $data, string $type): array
    {
        $data['password'] = $data['password'] ?? '';
        return $data;
    }

    protected function saveBefore(Admin $model, string $type): string
    {
        if (!in_array($type, ['add', 'edit'])) return '';
        $deptId = $this->request->post('deptId', '');
        if (!$deptId) return '请选择所属部门机构';
        if ($type == 'edit' && $model->id == $this->app->params['root_admin_id']) {
            return '超级管理员无法编辑';
        }
        if ($model->password) {
            $model->password = Admin::encryptPassword($model->password);
        } else {
            $model->password = $model->oldAttributes['password'];
        }
		$model->nick_name = $model->nick_name ?: $model->user_name;
        return '';
    }

    protected function saveAfter(Admin $model, string $type): void
    {
        if (!in_array($type, ['add', 'edit'])) return;
        $roleIds = $this->request->post('roleIds', '');
        $postIds = $this->request->post('postIds', '');
        $deptId = $this->request->post('deptId', '');

        AdminService::updateAdminRoleIds($model->id, $roleIds);
        AdminService::updateAdminPostIds($model->id, $postIds);
        AdminService::updateAdminDeptIds($model->id, $deptId);
    }

    protected function deleteBefore(Admin $model, string $type): string
    {
        if ($model->id == $this->app->params['root_admin_id']) return '超级管理员无法删除';
        return '';
    }

    /**
     * 重置密码
     * @return array
     */
    public function actionResetPwd(): array
    {
        $id = intval($this->request->post('id', 0));
        if ($id < 1) return $this->error('用户参数错误');
        $password = trim($this->request->post('password', ''));
        if (strlen($password) < 6 || strlen($password) > 20) return $this->error('密码长度为6-20字符');
        $info = Admin::findOne($id);
        if (!$id) return $this->error('用户信息不存在');
        $info->password = Admin::encryptPassword($password);
        if ($info->save(false)) return $this->success();
        return $this->error();
    }

    /**
     * 保存用户分配角色
     * @return array
     */
    public function actionAuthRole(): array
    {
        $id = intval($this->request->post('id', 0));
        if ($id < 1) return $this->error('用户参数错误');
        $roleIds = trim((string)$this->request->post('roleIds',''));
        if (!$roleIds) return $this->error('至少选中一个角色');
        if(AdminService::updateAdminRoleIds($id, $roleIds)) {
            return $this->success();
        }
        return $this->error();
    }

    protected function exportBefore(array $list): array
    {
        $row = [
            'id' => '编码',
            'user_name' => '账号',
            'nick_name' => '昵称',
            'email' => '邮箱',
            'update_time' => '更新时间'
        ];
        $bold = ['A1:E1' => true];

        return ['list' => $list, 'row' => $row, 'fileName' => '人员列表', 'bold' => $bold];
    }
}
